package com.dt.global.web.action.randomcode;

import java.awt.Color;
import java.awt.Font;
import java.awt.Graphics;
import java.awt.image.BufferedImage;
import java.io.ByteArrayInputStream;
import java.io.ByteArrayOutputStream;

import javax.imageio.ImageIO;
import javax.imageio.stream.ImageOutputStream;
import javax.servlet.http.HttpSession;

import com.dt.components.exstruts.action.BaseActionSupport;

/**
 * 验证码的Action
 * @author MWG
 *
 */
public class RandomCodeAction extends BaseActionSupport{
	/**
	 * 
	 */
	private static final long serialVersionUID = 1L;
	private ByteArrayInputStream inputStream; 
	public String execute()throws Exception{
		   //创建画板
		   int width = 58;
		   int height = 22;
		BufferedImage image=new BufferedImage(width,height,BufferedImage.TYPE_INT_RGB);
		//获得画笔
		Graphics g=image.getGraphics();
		 //产生随机背景颜色
		g.setColor(Color.decode("#E4F0F4"));
		g.fillRect(1,1,56,20);
		String str="1234567890";
		HttpSession s=getRequest().getSession();
		char[] cs=str.toCharArray();
		String code="";
		for(int i=0;i<4;i++){
			String showStr=cs[generateCode(cs.length)]+"";
			code=code+showStr.trim();
			g.setFont(new Font("Times New Roman",Font.PLAIN,17));
			g.setColor(Color.RED);
			g.drawString(showStr,13 * i + 6,18);
		}
		 //画字符串
		 g.setFont(new Font("Dialog",Font.PLAIN,15));
		 s.setAttribute("code",code);
         g.dispose();   
         ByteArrayOutputStream output = new ByteArrayOutputStream();   
		 ImageOutputStream imageOut = ImageIO.createImageOutputStream(output);   
	     ImageIO.write(image, "JPEG", imageOut);   
		 imageOut.close();   
		 ByteArrayInputStream input = new ByteArrayInputStream(output.toByteArray());   
		 this.setInputStream(input);  
		return SUCCESS;
	}
	private int generateCode(int num){//产生随机数 颜色
		   return (int)(Math.random()*num);
	   }
	public ByteArrayInputStream getInputStream() {
		return inputStream;
	}
	public void setInputStream(ByteArrayInputStream inputStream) {
		this.inputStream = inputStream;
	}
	
}
